/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package kaindorfcompany.webshop.productmanagement.backend.access;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

import kaindorfcompany.webshop.productmanagement.backend.access.sql.RawStatement;

public class AdvancedConnection {

    private Connection con;
    private final HashMap<Integer, PreparedStatement> preparedStatements;

    public AdvancedConnection(Connection con) {
        preparedStatements = new HashMap<Integer, PreparedStatement>();
        this.con = con;
    }

    public PreparedStatement prepareStatement(RawStatement stmt) throws SQLException {
        return stmt.prepareOn(con);
    }

    public PreparedStatement prepareStatement(Integer key, String sql, boolean generatedKeysEnabled)
            throws SQLException {
        PreparedStatement statement = con.prepareStatement(sql, generatedKeysEnabled ? Statement.RETURN_GENERATED_KEYS
            : Statement.NO_GENERATED_KEYS);
        putPreparedStatement(key, statement);
        return statement;
    }

    public void putPreparedStatement(Integer key, PreparedStatement statement) {
        if (statement == null) {
            throw new IllegalArgumentException("statement can not be null");
        }
        try {
            if (statement.getConnection() != con) {
                throw new IllegalArgumentException(
                    "The prepared statement has not been created by the current connection");
            }
        } catch (SQLException e) {
            throw new IllegalArgumentException("Error while checking prepared statement: " + e.getMessage(), e);
        }
        preparedStatements.put(key, statement);
    }

    public PreparedStatement getPreparedStatement(Integer key) {
        return preparedStatements.get(key);
    }

    public boolean containsStatement(Integer key) {
        return preparedStatements.containsKey(key);
    }

    public Connection getConnection() {
        return con;
    }
}
